#include "biscuit.h"
#include "putfunc.h"

char digits[] = "0123456789ABCDEF";
#define PUT_BUFSZ 64 
void reverse (char * s, int i);

void
putc (char c) {
    ll_putc (c);
}

void
puts (char * s) {
    while (*s) {
        putc (*s);
        s++;
    }
}

void
putd (int d) {
    // char buffer[PUT_BUFSZ];
    unsigned int u;
    if (d < 0) {
        u = d;
        u = ~u;
        u += 1;
        putc('-');
    } else {
        u = d;
    }
    putu (u);
}


void
putx (unsigned int x) {
    char buffer[PUT_BUFSZ];
    int i;
    for (i = 0; i < PUT_BUFSZ; i++)
        buffer[i] = 0;
    if (x == 0) {
        buffer[0] = '0';
        goto print;
    }
    i = 0;
    while (x) {
        if (i == PUT_BUFSZ-1) { // should never happen
            buffer[PUT_BUFSZ-1] = 0;
            reverse (buffer, i);
            goto print;
        }
        buffer[i++] = digits[x%16];
        x/=16;
    }
    reverse (buffer, i);
    print:
    puts (buffer);
}

void
putu (unsigned int u) {
    char buffer[PUT_BUFSZ];
    int i;
    for (i = 0; i < PUT_BUFSZ; i++)
        buffer[i] = 0;
    if (u == 0) {
        buffer[0] = '0';
        goto print;
    }
    i = 0;
    while (u) {
        if (i == PUT_BUFSZ-1) { // should never happen
            buffer[PUT_BUFSZ-1] = 0;
            reverse (buffer, i);
            goto print;
        }
        buffer[i++] = digits[u%10];
        u/=10;
    }
    reverse (buffer, i);
    print:
    puts (buffer);
}

void
reverse (char * s, int i) {
    int j, tmp;
    j = i-1;
    for (i = 0; i <= j/2; i++) {
        tmp = s[i];
        s[i] = s[j-i];
        s[j-i] = tmp;
    }
}

void
putp (void * p) {
    unsigned int x = (unsigned int) p;
    putx (x); 
} 
